import os

from coin.proto.coin_order_gateway_pb2 import OrderGatewayLog, OrderEvent
from coin.proto.coin_order_enums_pb2 import (BUY_ORDER,
                                             SELL_ORDER,
                                             UNKNOWN_ORDER_SIDE,
                                             BUY_OPEN_ORDER,
                                             BUY_CLOSE_ORDER,
                                             SELL_OPEN_ORDER,
                                             SELL_CLOSE_ORDER)


def get_order_event_dir(root_path, machine, trading_date, exchange, owner, market_type):
  td_str = trading_date.strftime('%Y%m%d')
  dir_path = os.path.join(root_path, machine, td_str, exchange, owner, market_type)
  return dir_path


def convert_event_type(event_type):
  if event_type in (1, '1', 'ORDER_SUBMITTED'):
    event_type = OrderEvent.ORDER_SUBMITTED
  elif event_type in (2, '2', 'ORDER_ACCEPTED'):
    event_type = OrderEvent.ORDER_ACCEPTED
  elif event_type in (3, '3', 'ORDER_ERROR'):
    event_type = OrderEvent.ORDER_ERROR
  elif event_type in (4, '4', 'ORDER_FILLED'):
    event_type = OrderEvent.ORDER_FILLED
  elif event_type in (8, '8', 'ORDER_REJECTED'):
    event_type = OrderEvent.ORDER_REJECTED
  elif event_type in (11, '11', 'CANCEL_SUBMITTED'):
    event_type = OrderEvent.CANCEL_SUBMITTED
  elif event_type in (12, '12', 'CANCEL_ACCEPTED'):
    event_type = OrderEvent.CANCEL_ACCEPTED
  elif event_type in (13, '13', 'CANCEL_ERROR'):
    event_type = OrderEvent.CANCEL_ERROR
  elif event_type in (14, '14', 'CANCEL_CONFIRMED'):
    event_type = OrderEvent.CANCEL_CONFIRMED
  else:
    print('Unknown order event type: %s' % event_type)
    event_type = OrderEvent.UNKNOWN_ORDER_EVENT
  return event_type


def convert_order_side(order_side):
  if order_side in (1, '1', 'BUY_ORDER'):
    order_side = BUY_ORDER
  elif order_side in (2, '2', 'SELL_ORDER'):
    order_side = SELL_ORDER
  elif order_side in (3, '3', 'BUY_OPEN_ORDER'):
    order_side = BUY_OPEN_ORDER
  elif order_side in (4, '4', 'BUY_CLOSE_ORDER'):
    order_side = BUY_CLOSE_ORDER
  elif order_side in (5, '5', 'SELL_OPEN_ORDER'):
    order_side = SELL_OPEN_ORDER
  elif order_side in (6, '6', 'SELL_CLOSE_ORDER'):
    order_side = SELL_CLOSE_ORDER
  else:
    print('Unknown order side: %s' % order_side)
    order_side = UNKNOWN_ORDER_SIDE
  return order_side
